# -*- coding: utf-8 -*-
# created on 2017/04/25

from sympy import Union, sympify
from mathsolver.functions.base import BaseFunction, new_latex, BaseSymbolValue, BaseIneq
from mathsolver.functions.budengshi.jiebudengshi import JieBuDengShi
from mathsolver.functions.hanshu.helper import cal_canshu_from_expr
from mathsolver.functions.hanshu.zuizhi_new import MinMaxValue


class AbsFMaxMinBuDengShi(BaseFunction):
    """077.|f(x_1) - f(x_2)| ≤(<) g(a)型"""

    def solver(self, *args):
        func, belongs, funceq = args
        canshu = cal_canshu_from_expr(func.expression)
        interval = belongs.interval[0]
        funceq_left, op, funceq_right = funceq.value

        # 转化成最值问题
        funceq_right = sympify(funceq_right)
        self.steps.append(["", "由定义知对于 x ∈ %s 有 f(x)_{max} - f(x)_{min} %s %s" %
                           (new_latex(interval), op, new_latex(funceq_right))])

        # 求最值
        minmax_solver = MinMaxValue().solver(func, interval)
        self.steps.extend(minmax_solver.steps)
        combine_result = minmax_solver.output[0].value

        # TODO: 可能需要补充，目前只考虑最大、小值都取得到的情况，其他的先不考虑
        result = []
        for _canshu_range, _others in combine_result.items():
            (min_val, (min_xval, min_reacheable)), (max_val, (max_xval, max_reacheable)) = _others
            assert min_reacheable and max_reacheable, "目前只考虑最大、小值都取得到的情况"
            budengshi_solver = JieBuDengShi().solver(BaseIneq([max_val - min_val, op, funceq_right])).output[0]
            self.steps.append(["", "当 %s ∈ %s 时，解不等式得 %s"
                               % (str(canshu), new_latex(_canshu_range), budengshi_solver.printing())])
            result.append(budengshi_solver.value.values()[0].intersect(_canshu_range))

        output_result = BaseSymbolValue({canshu: Union(*result)})
        self.steps.append(['', "所以最终参数的取值范围为 %s " % output_result.printing()])
        self.label.add("|f(x_1) - f(x_2)| ≤(<) g(a)型问题")
        return self


if __name__ == '__main__':
    pass
